import re


from rest_framework import serializers

from django_redis import get_redis_connection

from app_user.utils import to_md5_hex
from xuanba_model.models import Users


class RegisterCreateSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8, max_length=20,  write_only=True)
    sms_code = serializers.CharField(min_length=6, max_length=6,  write_only=True)
    captcha = serializers.CharField(min_length=4, max_length=4, write_only=True)

    class Meta:
        model = Users
        fields = ('user_name', 'password', 'password2', 'tel', 'sms_code',
                  'captcha')

        extra_kwargs = {
            "password": {
                "min_length": 8,
                "max_length": 20,
                "write_only": True
            },
            "user_name": {
                "min_length": 5,
                "max_length": 20,
                "write_only": True
            },
            "tel": {
                "min_length": 11,
                "max_length": 11,
                "write_only": True
            },
        }

    def validate(self, attrs):
        sms_code = attrs['sms_code']
        tel = attrs['tel']
        captcha = attrs['captcha']

        TEL_PATTERN = re.compile(r'1[356789]\d{9}')
        if not TEL_PATTERN.fullmatch(attrs['tel']):
            raise serializers.ValidationError('手机号格式不符合规范')

        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不相等')

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_%s" % tel)
        redis_captcha = redis_conn.get("img_%s" % attrs['user_name'])

        if not redis_sms_code:
            raise serializers.ValidationError('短信验证码已经过期')

        if redis_sms_code.decode().lower() != sms_code.lower():
            raise serializers.ValidationError('短信验证码填写错误')

        if not redis_captcha:
            raise serializers.ValidationError('图片验证码已经过期')

        if redis_captcha.decode() != captcha:
            raise serializers.ValidationError('短信验证码填写错误')

        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['captcha']
        user = super(RegisterCreateSerializer, self).create(validated_data)
        user.password = to_md5_hex(validated_data['password'])
        user.alias = user.user_name
        user.save()
        return user
